/*
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-12 15:50:21
 * @LastEditors: xuebao
 * @LastEditTime: 2023-12-13 21:07:57
 */
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { Form, Input, InputNumber, Modal, Select, TreeSelect, Upload } from 'antd'
import { getItem } from '@/utils/storage'
import type { RcFile, UploadChangeParam, UploadFile, UploadProps } from 'antd/es/upload/interface'
import { useEffect, useImperativeHandle, useState } from 'react'
import { message } from '@/utils/AntdGlobal'
import { IAction, IModalProp } from '@/types/modal'
import { Dept, Role, User } from '@/types/api'
import api from '@/api'
import roleApi from '@/api/roleApi'
const CreateUser = (props: IModalProp) => {
  const [userId, setUserId] = useState<number | string>()
  const [form] = Form.useForm()
  const [visible, setVisible] = useState(false)
  const [action, setAction] = useState<IAction>('create')
  const [img, setImg] = useState<string>()
  const [loading, setLoading] = useState(false)
  const [deptList, setDeptList] = useState<Dept.DeptItem[]>()
  const [roleList, setRoleList] = useState<Role.RoleItem[]>()
  //暴露子组件open方法
  useImperativeHandle(props.mRef, () => {
    return {
      open,
    }
  })
  useEffect(() => {
    getDeptList()
    getRoleList()
  }, [])
  //获取部门列表
  const getDeptList = async () => {
    const data = await api.getDeptList()
    setDeptList(data)
  }
  //获取所有角色列表
  const getRoleList = async () => {
    const data = await roleApi.getAllRoleList()
    setRoleList(data)
  }
  //调用弹窗打开方法
  const open = (type: IAction, data?: User.UserItem) => {
    setAction(type)
    setVisible(true)
    if (type === 'edit' && data) {
      //回填edit的信息
      setImg(data.userImg)
      setUserId(data.userId)
      form.setFieldsValue({ ...data, userId })
    }
  }
  //提交
  const handleSubmit = async () => {
    const valid = await form.validateFields()
    if (valid) {
      //调用
      const params = {
        ...form.getFieldsValue(), //获取到所有的值,
        userImg: img,
      }
      if (action === 'create') {
        //创建
        await api.createUser(params)
        message.success('创建成功')
      } else {
        await api.editUser({ ...params, userId })
        message.success('修改成功')
      }
      handleCancel()
      props.update() //触发外面父组件用户列表
    }
  }
  //上传之后
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    const { code, data, msg } = info.file.response
    if (info.file.status === 'done') {
      if (code == 0) {
        //上传成功保存图片
        setImg(data.file)
        setLoading(false)
      } else {
        message.error(msg)
      }
    } else if (info.file.status === 'error') {
      message.error('服务器异常，请稍后重试')
    }
  }
  //上传之前
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG图片')
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 0.5
    if (!isLt2M) {
      message.error('不能超过500K!')
    }
    return isJpgOrPng && isLt2M
  }

  //关闭弹窗
  const handleCancel = () => {
    setVisible(false)
    //重置form
    form.resetFields()
    setImg('') //清空头像
    setUserId('')
  }
  return (
    <Modal
      title={action === 'create' ? '创建用户' : '编辑用户'}
      open={visible}
      okText='确定'
      cancelText='取消'
      width={800}
      onOk={handleSubmit}
      onCancel={handleCancel}
    >
      <Form labelCol={{ span: 4 }} labelAlign='right' form={form}>
        <Form.Item
          label='用户名'
          name='userName'
          rules={[
            { required: true, message: '请输入用户名称' },
            {
              min: 5,
              max: 12,
              message: '用户名长度为5-12位',
            },
          ]}
        >
          <Input placeholder='请输入用户名' />
        </Form.Item>
        <Form.Item
          label='用户邮箱'
          name='userEmail'
          rules={[
            { required: true, message: '请输入邮箱' },
            {
              pattern: /^\w+@qq.com$/,
              message: '邮箱必须@qq.com结尾',
            },
          ]}
        >
          <Input placeholder='请输入用户@qq.com结尾的邮箱' disabled={action === 'edit'} />
        </Form.Item>
        <Form.Item
          label='手机号'
          name='mobile'
          rules={[
            { len: 11, message: '手机号必须11位数字' },
            {
              pattern: /1[1-9]\d{9}/,
              message: '手机号必须为1开头的11位数字',
            },
          ]}
        >
          <Input type='number' placeholder='请输入手机号'></Input>
        </Form.Item>
        <Form.Item label='部门' name='deptId' rules={[{ required: true, message: '请输入部门' }]}>
          <TreeSelect
            placeholder='请选择部门'
            allowClear
            treeDefaultExpandAll
            showCheckedStrategy={TreeSelect.SHOW_ALL}
            fieldNames={{
              label: 'deptName',
              value: '_id',
            }}
            treeData={deptList}
          ></TreeSelect>
        </Form.Item>
        <Form.Item label='岗位' name='job'>
          <Input placeholder='请输入岗位' />
        </Form.Item>
        <Form.Item label='状态' name='state'>
          <Select placeholder='请输入状态'>
            <Select.Option value={1}>在职</Select.Option>
            <Select.Option value={2}>离职</Select.Option>
            <Select.Option value={3}>试用期</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label='系统角色' name='roleList'>
          <Select placeholder='请选择角色'>
            {roleList?.map((item) => {
              return (
                <Select.Option key={item._id} value={item._id}>
                  {item.roleName}
                </Select.Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item label='用户头像'>
          <Upload
            listType='picture-circle'
            showUploadList={false}
            action='/api/users/upload'
            beforeUpload={beforeUpload}
            onChange={handleChange}
            headers={{ Authorization: 'Bearer ' + getItem('token'), icode: '346C9858606AB989' }}
          >
            {img ? (
              <img src={img} style={{ width: '100%', borderRadius: '100%' }} />
            ) : (
              <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 5 }}>上传头像</div>
              </div>
            )}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default CreateUser
